package com.chen.proxyReviw.dto.impl;

import com.chen.proxyReviw.dto.User;
import com.chen.proxyReviw.server.UserService;

import java.util.ArrayList;
import java.util.List;

public class UserServiceImpl implements UserService {
    private static final List<User>  users = new ArrayList<User>();
    private static int count;

   static {
        for (int i = 0; i < 100000; i++) {
            users.addAll(List.of(
                    new User(count++, "username1", "123443", 89),
                    new User(count++, "username1", "123", 4),
                    new User(count++, "username1", "123", 4),
                    new User(count++, "username1", "123", 4)));
        }
    }

//    public static void main(String[] args) {
//        User user = new User(1, "chen", "123", 4);
//        UserServiceImpl userService = new UserServiceImpl();
//        userService.printArray();
//        userService.update(user);
//        System.out.println("==================");
//        userService.printArray();
//    }

    @Override
    public List<User> findAll() {
       List<User> list=new ArrayList<>();
       for (User user : users) {
           list.add(user);
       }
        return list;
    }

    @Override
    public User findById(int id) {
        return users.stream().filter(user -> user.getId() == id)
                .findFirst().orElse(null);
    }

    @Override
    public void save(User user) {
        users.add(user);
    }

    @Override
    public void update(User user) {
        users.replaceAll(s->{
            if (user.getId() == s.getId()) {
                return user;
            }
            return s;
        });
    }

    @Override
    public void delete(int id) {
        users.removeIf(user -> user.getId() == id);
    }

    public void printArray() {
        for (User user : users) {
            System.out.println(user);
        }
    }
}
